package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.PageResult;
import com.itheima.constant.QueryBean;
import com.itheima.constant.QueryPageBean;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.domain.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/9/27 14:15
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 添加数据;
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //编辑setmeal表中的数据;
        setmealDao.add(setmeal);
        //获取添加的对象ID;
        Integer setmealId = setmeal.getId();
        //操作中间表;
        //先判断数组中有没有元素;
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                //创建一个map集合用于存放数据;
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealIdAndCheckGroupId(map);
            }

        }
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);

    }

    /**
     * 分页条件查询
     *
     * @param queryBean
     * @return
     */
    @Override
    public PageResult findPage(QueryBean queryBean) {
        Integer currentPage = queryBean.getCurrentPage();
        Integer pageSize = queryBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Map<String, Object> map = queryBean.getMap();
        Page<Setmeal> page = setmealDao.findPage(map);
        List<Setmeal> rows = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, rows);
    }


    /*
     *
     * 查询全部;
     * */
    @Override
    public List<Setmeal> findAll() {

        return setmealDao.findAll();
    }


    /**
     * 根据ID查询;
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }
}
